/*  shiro Realm 授权认证 ：  yjj  */

package com.woniuxy.main.realm;

import java.util.ArrayList;
import java.util.Collection;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import com.woniuxy.main.login_yjj.pojo.LoginUser;
import com.woniuxy.main.login_yjj.pojo.User_Yjj;
import com.woniuxy.main.login_yjj.service.LoginService;

import lombok.Data;


@Data
public class UserRealm extends AuthorizingRealm{
	@Autowired
	private LoginService service;
	
	
	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("授权中...");
		String my=(String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo sthor=new SimpleAuthorizationInfo();
		Collection<String> permissions=new ArrayList<String>();
		User_Yjj lu=service.findUserByPhone(my);
		//根据数据库查询出的角色，添加各种权限
		if(lu.getRole_id()==1) {
			permissions.add("user");
		}
		if(lu.getRole_id()==2) {
			permissions.add("coach");
		}
        if(lu.getRole_id()==3) {
        	permissions.add("venue");
		}
        if(lu.getRole_id()==4) {
			permissions.add("supper");
		}
		sthor.addStringPermissions(permissions);
		return sthor;
	}
	
	
	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("正在进行认证...");
		//获取账号
		String phone = (String)token.getPrincipal();
		//查询数据库
		LoginUser user = service.finduser(new LoginUser(phone,null,0,0));
		if (user!=null) {
			SimpleAuthenticationInfo info 
				= new SimpleAuthenticationInfo(phone, user.getUser_pwd(),this.getName());
			return info;
		}
		return null;
	}
	
	
}
